<template>
	<view>
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" title="提醒" :content="dialogValue" @confirm="dialogInputConfirm"></uni-popup-dialog>
		</uni-popup>
		<u-popup :show="showCodeAdd" mode="top" @close="closeAddress">
			<view style="max-height: 1000rpx; overflow: auto">
				<view class="content-box" v-for="(item, index) in codeAddressDat" @click="changeAddress(item)">
					<!-- <uni-tag v-show="item.sort == 1" :inverted="true" text="标签" type="primary" /> -->
					<!-- <u-tag class="tagU" :show="index == 0" text="默认" plain></u-tag> -->
					<view class="content-leftTop">
						<text class="content-text">{{ item.userName }}</text>
						<text style="width: 200rpx" class="content-text">{{ item.phone }}</text>
					</view>
					<text class="content-text">{{ item.text }}</text>
				</view>
			</view>
		</u-popup>
		<u-popup :show="showAdd" mode="bottom" @close="closeAddress">
			<view style="max-height: 1000rpx; overflow: auto">
				<view class="content-box" v-for="(item, index) in addressList" @click="changeAddress(item)">
					<!-- <uni-tag v-show="item.sort == 1" :inverted="true" text="标签" type="primary" /> -->
					<u-tag class="tagU" :show="index == 0" text="默认" plain></u-tag>
					<view class="content-leftTop">
						<text class="content-text">{{ item.userName }}</text>
						<text style="width: 200rpx" class="content-text">{{ item.phone }}</text>
					</view>
					<text class="content-text">{{ item.text }}</text>
				</view>
			</view>
			<view class="">
				<button @click="ToAddressPage">管理地址</button>
			</view>
		</u-popup>
		<u-loading-page :loading="showsubLoading" loading-text="loading..."></u-loading-page>
		<uni-section v-if="!showsubLoading">
			<view class="example">
				<uni-forms ref="form" :rules="rules">
					<uni-forms-item label="标题"  label-align="right"  name="name" required>
						<uni-easyinput type="text" v-model="titleTxt" placeholder="请输入工单标题" />
					</uni-forms-item>
					<uni-forms-item label="内容" label-align="right"  name="content" required>
						<picker  @change="comPickerChange" :value="indexL" :range="arryL" range-key="text">
							<view class="uni-input">{{ arryL[index].text }}</view>
						</picker>
						<!-- <button @click="comLanguage">常用语</button> -->
						<uni-easyinput type="textarea" v-model="contentTxt" placeholder="请输入报修内容" />
					</uni-forms-item>
					<uni-forms-item label="紧急程度" label-width="80px" label-align="right"  name="priority" required>
						<uni-data-checkbox v-model="priorityValue" :localdata="priorityData" />
					</uni-forms-item>
					<uni-forms-item label="工单类型"  label-width="80px" label-align="right"  required name="workTypeId">
						<view class="uni-list-cell">
							<uni-data-select v-model="workTypeId" :localdata="array" @change="bindPickerChange"></uni-data-select>
						</view>
					</uni-forms-item>
					<uni-forms-item label="图片" label-align="right"  name="picture">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10"></u-upload>
					</uni-forms-item>
					<uni-forms-item label="视频" label-align="right"  name="video">
						<u-upload
							:fileList="fileList2"
							@afterRead="afterRead"
							@delete="deletePic"
							name="2"
							multiple
							:maxCount="10"
							accept="video"
							:previewFullImage="true"
						></u-upload>
					</uni-forms-item>
					<uni-forms-item label="音频" label-align="right"  class="voiceClass">
						<nb-voice-record @startRecord="start" @endRecord="end" @cancelRecord="cancel"></nb-voice-record>
					</uni-forms-item>
					<uni-forms-item label="区域" label-align="right"  name="name">
						<view class="content-box" @click="showAdd = true">
							<!-- <uni-tag v-show="item.sort == 1" :inverted="true" text="标签" type="primary" /> -->
							<u-tag class="tagU" :show="addressData.sort == 1" text="默认" plain></u-tag>
							<view class="content-leftTop">
								<text class="content-text">{{ addressData.userName }}</text>
								<text style="width: 200rpx" class="content-text">{{ addressData.phone }}</text>
							</view>
							<text class="content-text">{{ addressData.text }}</text>
						</view>
					</uni-forms-item>
					<button @click="Scode">扫码</button>
				</uni-forms>
			</view>
		</uni-section>
		<button v-if="!showsubLoading" class="subMittt" @click="SubmitOrder">提交</button>
	</view>
</template>

<script>  
import { uploadFile, getMyworkInfo, getWorkclass, getdeviceInfoCode, getDeptCascade, getLanguages, editorMyworkInfo, getAddressList } from '@/api/system/user.js';
import store from '@/store/index.js';
export default {
	data() {
		return {
			rules: {
				name: {
					rules: [
						{
							required: true,
							errorMessage: '标题不能为空',
						}
					]
				},
				priority: {
					rules: [
						{
							required: true,
							errorMessage: '不能为空'
						}
					]
				}
			},
			addressId: '',
			QzoneId: '',
			showAdd: false,
			showCodeAdd: false,
			fileList1: [], //图片list
			fileList2: [], //视频list
			informId: '',
			classes: '',
			codeData: '', //二维码
			deviceData: '',
			addressList: '', //地址list
			addressData: '',
			imageValue: [],
			picTxt: '',
			videoValue: [],
			videoTxt: '',
			WorkClass: '',
			myWorkInfom: '',
			index: 0,
			indexL: 0,
			array: [],
			arryL: [],
			workTypeId: '',
			contentTxt: '',
			VoiceValue: '',
			UserId: '',
			DeptId: '',
			dialogValue: '',
			codeAddressDat: '',
			msgType: 'success',
			messageText: '这是一条成功提示',
			titleTxt: '',
			dataTree: '',
			zoneIdNum: '',
			priorityValue: 2,
			videoMo: '',
			showsubLoading: false,
			// 单选数据源
			priorityData: [
				{
					text: '次要',
					value: 1
				},
				{
					text: '普通',
					value: 2
				},
				{
					text: '紧急',
					value: 3
				}
			]
		};
	},
	onLoad(options) {
		// console.log(options.id);
		if (options.id) {
			// this.$nextTick(() => {
			this.myWorkInfom = store.state.myInform;
			if (this.myWorkInfom.picture == null) {
				this.FileList2 = [];
			} else {
				this.myWorkInfom.picture.split(',').map((item) => {
					this.fileList1.push({
						url: item,
						status: 'success', 
						message: ''
					});
				});
			}
			if (this.myWorkInfom.video == null) {
				this.FileList2 = [];
			} else {
				this.myWorkInfom.video.split(',').map((item) => {
					this.fileList2.push({
						url: item,
						status: 'success',
						message: ''
					});
				});
			}

			// this.myWorkInfom.picture.split(',')
			this.informId = this.myWorkInfom.id;
			this.workTypeId = this.myWorkInfom.worderClass.typeId;
			this.titleTxt = this.myWorkInfom.title;
			this.contentTxt = this.myWorkInfom.content;
			this.VoiceValue = this.myWorkInfom.voice;
			this.deviceData = this.myWorkInfom.deviceId;
			this.classes = JSON.stringify(this.myWorkInfom.zoneId);
			this.priorityValue = this.myWorkInfom.priority;
			this.addressId = this.myWorkInfom.addressId;
			// console.log('myform', options.id);
			// });
		}

		this.getWorkClass();
	},
	onShow() {
		if (store.state.reflash) {
			this.getWorkClass();
			store.state.reflash = false;
		}
	},
	// watch: {
	// 	classes(newVal, oldVal) {
	// 		console.log('newVal', newVal);
	// 		console.log('oldVal', oldVal);
	// 	}
	// },
	methods: {
		async getWorkClass() {
			try {
				this.UserId = uni.getStorageSync('userID');
				this.DeptId = uni.getStorageSync('DeptId');
				if (this.DeptId) {
					console.log(this.DeptId);
				}
			} catch (e) {
				// error
			}
			await getAddressList(this.UserId).then((res) => {
				console.log(res);
				this.addressList = res.data;
			});
			if (this.myWorkInfom) {
				this.addressData = this.addressList.filter((item) => item.id == this.myWorkInfom.addressId)[0];
				console.log('addressData11', this.addressData);
			} else {
				this.addressData = this.addressList[0];
				this.addressId = this.addressList[0].id;
				console.log('addressData', this.addressData);
			}
			// this.classes = store.state.myInform.zoneId;
			getDeptCascade(this.DeptId).then((res) => {
				this.dataTree = res.data;
				// this.classes = this.myWorkInfom.zoneId;
				// console.log('classes', this.classes);
			});
			getWorkclass().then((res) => {
				this.array = res.data.filter((item) => item.pId > 0);
				this.array = this.array.map((item) => {
					return {
						text: item.typeName,
						value: item.typeId
					};
				});
				let num = 0;
				this.array.map((item) => {
					if (item.typeId == this.workTypeId) {
						this.index = num;
					}
					num += 1;
				});

				// this.array = res.rows;
				// this.workTypeId = this.array[1].typeId;
				// console.log('getWorkclass:', this.array);
			});
			getLanguages(this.UserId).then((res) => {
				// console.log('getLanguages', res);
				this.arryL = res.data;
			});
		},
		Scode() {
			var _this = this;
			// 只允许通过相机扫码
			uni.scanCode({
				onlyFromCamera: true,
				success: function (res) {
					console.log('条码类型：' + res.scanType);
					console.log('条码内容：' + res.result);
					_this.codeData = res.result;
					_this.getDeviceCode();
				}
			});

			// console.log('res.result:', _this.codeData);
		},
		getDeviceCode() {
			getdeviceInfoCode(this.codeData).then((res) => {
				if (res.data == '') {
					this.dialogValue = '无效二维码，查询不到此设备';
					this.inputDialogToggle();
					return false;
				} else {
					console.log('deviceData', res);
					this.deviceData = res.data[0].id;
					this.QzoneId = res.data[0].aid;
					this.workTypeId = res.data[0].wid;
					this.codeAddressDat = this.addressList.filter((item) => item.zoneId == res.data[0].aid);
					console.log('this.codeAddressDat', this.codeAddressDat);
					if (this.codeAddressDat.length > 1) {
						this.showCodeAdd = true;
					} else if (this.codeAddressDat.length == 1) {
						this.addressId = this.codeAddressDat[0].id;
						this.addressData = this.codeAddressDat[0];
					} else {
						this.dialogValue = '未找到该设备对应地址，是否前往添加地址？';
						this.inputDialogToggle();
					}
					// this.inputDialogToggle();
				}
				// if (res.code == 200) {

				// } else {
				// 	this.inputDialogToggle();
				// }
			});
		},
		inputDialogToggle() {
			this.$refs.inputDialog.open();
		},
		dialogInputConfirm(val) {
			console.log('QzoneId', this.QzoneId);
			uni.navigateTo({
				url: `/pages/mine/address/index?zoneId=${this.QzoneId}`
			});
			// uni.showLoading({
			// 	title: '扫码成功'
			// });

			// setTimeout(() => {
			// 	uni.hideLoading();
			// 	console.log(val);
			// 	this.value = val;
			// 	// 关闭窗口后，恢复默认内容
			// 	this.$refs.inputDialog.close();
			// }, 300);
		},
		// 删除图片
		deletePic(event) {
			this[`fileList${event.name}`].splice(event.index, 1);
		},
		// 新增图片
		async afterRead(event) { 
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			// const result = '';
			for (let i = 0; i < lists.length; i++) {
				const result = await uploadFile(lists[i].url).then((res) => {
					// console.log(res);
					return res.url;
				});
				let item = this[`fileList${event.name}`][fileListLen];
				this[`fileList${event.name}`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					})
				);
				fileListLen++;
				console.log('fileList2', this.fileList2);
			}
		},
		// 获取上传状态
		select(e) {
			const tempFilePaths = e.tempFilePaths;
			// console.log('tempFilePaths:', tempFilePaths);
			tempFilePaths.map((item) => {
				let data = { filePath: item };
				console.log('data:', data);
				uploadFile(data).then((res) => {
					this.imageValue.push(res.url);
					console.log('上传成功：', res);
				});
			});
		},
		selectVideo(e) {
			const tempFilePaths = e.tempFilePaths;
			const imgUrl = tempFilePaths[0];
			console.log('video:', imgUrl);
			let data = { filePath: imgUrl };
			// console.log('data:', data);
			uploadFile(data).then((res) => {
				this.videoValue.push(res.url);
				// console.log('上传成功：', res);
			});
			// console.log('videoValue', this.videoValue);
			// console.log('选择文件：', this.videoMo);
		},
		start() {
			// 开始录音
		},
		end(event) {
			// console.log('event:', event);
			let data = event.tempFilePath;
			console.log('data:', data);
			uploadFile(data).then((res) => {
				this.VoiceValue = res.url;
				// this.videoValue.push(res.url);
				console.log('上传成功：', res);
			});
			// 结束录音并处理得到的录音文件
			// event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
		},
		cancel() {
			// 用户取消录音
		},
		bindPickerChange() {
			console.log('workTypeId', this.workTypeId);
		},
		comPickerChange: function (e) {
			console.log('picker发送选择改变，携带值为', e);
			this.indexL = e.detail.value;
			this.contentTxt += this.arryL[this.indexL].text;
			// console.log('this.workTypeId', this.workTypeId);
		},
		SubmitOrder() {
			if (this.titleTxt && this.contentTxt && this.workTypeId && this.priorityValue) {
				this.fileList1.map((item) => {
					this.imageValue.push(item.url);
				});
				this.fileList2.map((item) => {
					this.videoValue.push(item.url);
				});
				this.picTxt = this.imageValue.toString();
				this.videoTxt = this.videoValue.toString();
				let data = {
					id: this.informId,
					userId: this.UserId,
					typeId: this.workTypeId,
					addressId: this.addressId,
					title: this.titleTxt,
					content: this.contentTxt,
					video: this.videoTxt,
					picture: this.picTxt,
					voice: this.VoiceValue,
					deviceId: this.deviceData,
					zoneId: this.classes,
					priority: this.priorityValue,
					state: 1
				};
				console.log('data', data);
				if (this.myWorkInfom) {
					editorMyworkInfo(data).then((res) => {
						this.messageToggle();
						this.showsubLoading = true;
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					});
				} else {
					getMyworkInfo(data).then((res) => {
						// console.log('提交成功', res);
						this.showsubLoading = true;
						this.messageToggle();
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					});
				}
				// console.log('zhengque');
			} else {
				this.msgType = 'error';
				this.messageText = `必填项不得为空`;
				this.$refs.message.open();
				console.log('内容缺失');
			}
		},
		messageToggle() {
			this.msgType = 'success';
			this.messageText = `提交成功`;
			this.$refs.message.open();
		},
		onnodeclick(e) {
			this.zoneIdNum = e.value;
			console.log(e);
			console.log('classes', this.classes);
		},
		changeAddress(item) {
			this.addressId = item.id;
			this.addressData = item;
			this.showAdd = false;
			this.showCodeAdd = false;
		},
		ToAddressPage() {
			this.$tab.navigateTo('/pages/mine/address/index');
		},
		closeAddress() {
			this.showAdd = false;
			this.showCodeAdd = false;
		},
		onpopupopened(e) {
			console.log('popupopened');
		},
		onpopupclosed(e) {
			console.log('popupclosed');
		},
		onchange(e) {
			console.log('onchange:', e);
		}
	}
};
</script>

<style lang="scss">
.example-body {
	padding: 10px;
	padding-top: 0;
}
nb-voice-record {
	// position: re;
	// position: fixed;
	// margin: 0 auto;
	// bottom: 200rpx;
	left: 50%;
	transform: translateX(-50%);
}
.subMittt {
	// position: fixed;
	// bottom: 50rpx;
	left: 50%;
	transform: translateX(-50%);
}
.content-box {
	flex: 1;
	/* #ifdef APP-NVUE */
	justify-content: center;
	/* #endif */
	// height: 88px;
	// line-height: 44px;
	padding: 15px 15px;
	position: relative;
	background-color: #fff;
	border-color: #00ffff;
	border-width: 2px;
	border-style: solid;
}
.content-leftTop {
	width: 350rpx;
	display: flex;
	justify-content: space-between;
}
.content-text {
	font-size: 15px;
}
.u-tag {
	position: absolute;
	right: 50rpx;
}
// .voiceClass{
// 	width: 50px;
// }
// .record-popup {
// 	left: 50% !important;
// 	transform: translateX(-50%);
// }
</style>
